﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using System.IO;

namespace Common.Reflection
{
    public static class ObjectExporter
    {
        public static void ExportPropertiesToFile(this object anonymousObject, string strFileName)
        {
            try
            {
                if (anonymousObject == null) return;
                if (String.IsNullOrEmpty(strFileName)) return;

                System.Type tSrcObject = anonymousObject.GetType();

                PropertyInfo[] pfSrcobjs = tSrcObject.GetProperties();
                List<string> strarylstofvars = new List<string>();

                Parallel.ForEach(pfSrcobjs, pitem =>
                    {
                        var pinfo = pfSrcobjs.Where(
                                                p =>
                                                    p.CanRead || p.CanWrite
                                                ).FirstOrDefault();

                        strarylstofvars.Add(pitem.Name);
                    }
                );

                File.WriteAllLines(strFileName, strarylstofvars.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void ExportVariablesToFile(this object anonymousObject, string strFileName)
        {
            try
            {
                if (anonymousObject == null) return;
                if (String.IsNullOrEmpty(strFileName)) return;

                System.Type tSrcObject = anonymousObject.GetType();

                FieldInfo[] pfSrcobjs = tSrcObject.GetFields();
                List<string> strarylstofvars = new List<string>();

                Parallel.ForEach(pfSrcobjs, pitem =>
                    {
                        var pinfo = pfSrcobjs.Where(
                                                p =>
                                                    p.IsPrivate == false
                                                ).FirstOrDefault();

                        strarylstofvars.Add(pitem.Name);
                    }
                );

                File.WriteAllLines(strFileName, strarylstofvars.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
